package com.hzb.LNReader;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;

import com.hzb.LNReader.convertor.HtmlParser;
import com.hzb.LNReader.convertor.HtmlToTxtConvertor;

public class FileSelectActivity extends Activity {
	static final String LOG = "FileSelectActivity";
	private static final String ICON = "icon";
	private static final String NAME = "name";
	private final String[] adapterFrom = new String[] {ICON, NAME};
	private final int[] adapterTo = new int[] {R.id.Icon, R.id.FileName};
	
	private File rootDir;
	private File currDir;
	
	private ListView fileView;
	private File[] currFileList;
	
	@Override
	protected void onResume() {
		super.onResume();
		
	}
	
	void openReader(String path) {
		Intent intent = new Intent(FileSelectActivity.this, ReaderActivity.class);
		intent.putExtra(ReaderActivity.DST_FILE, path);
		startActivity(intent);
		finish();
	}
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		rootDir = new File(ReaderContext.rootFolder);
		if (!rootDir.exists()) {
			if (!rootDir.mkdirs()) rootDir = new File("/sdcard");
		} else {
			if (!rootDir.isDirectory()) rootDir = new File("/sdcard");
		}
		if (!rootDir.exists()) rootDir = new File("/");
			
		
		fileView = new ListView(this);
		fileView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				File file = currFileList[position];
				if (file.isDirectory()) {
					updateFileList(file);
				} else {
					String name = convertHtmlFile(file);
					if (name != null) {
						openReader(name);
					}
				}
			}

			
		});
		fileView.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				return false;
			}
		});
			
		setContentView(fileView);
		updateFileList(rootDir);
	};
	
	private String convertHtmlFile(File file) {
		String name = file.getAbsolutePath();
		int dotIndex = name.lastIndexOf('.');
		if (dotIndex != -1) {
			dotIndex ++;
			String extendName = name.substring(dotIndex);
			if (extendName.equalsIgnoreCase("htm")
					|| extendName.equalsIgnoreCase("html")) {
				name = name.substring(0, dotIndex) + "lnd";
				File newFile = new File(name);
				if ((!newFile.isFile()) || newFile.lastModified() < file.lastModified()) {
					try {
						new HtmlParser(new HtmlToTxtConvertor(newFile)).parse(new FileInputStream(file));
					} catch (Exception e) {
						Builder dialog = new AlertDialog.Builder(this);
						dialog.setTitle("错误");
						dialog.setMessage("文件转换出错,请重新选择文件。");
						dialog.setPositiveButton("OK", new OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog, int which) {
								dialog.dismiss();
							}
						});
						dialog.show();
						
						Log.e(LOG, "Error converting html", e);
						return null;
					}
				}
			}
		}
		return name;
	}
	
	@Override
	public void onBackPressed() {
		if (rootDir.equals(currDir)) {
			if (ReaderContext.head == null) {
				ReaderContext.save();
				finish();
			} else {
				openReader(null);
			}
		} else {
			updateFileList(currDir.getParentFile());
		}
		
	}
	
	private static FileFilter filter = new ReaderFileFilter();
	void updateFileList(File parent) {
		try {
			File[] newFileList = parent.listFiles(filter);
			if (newFileList == null) {
				return;
			}
			currFileList = newFileList;
		} catch (Exception e) {
			Log.e(LOG, "Error listing dir", e);
			return;
		}
		
		currDir = parent;
		List<Map<String, Object>> adapterList = new ArrayList<Map<String,Object>>();
		for (File file : currFileList) {
			Map<String, Object> entry = new HashMap<String, Object>();
			if (file.isDirectory()) {
				entry.put(ICON, R.drawable.folder);
			} else {
				entry.put(ICON, R.drawable.file);
			}
			entry.put(NAME, file.getName());
			adapterList.add(entry);
		}
		SimpleAdapter fileAdapter = new SimpleAdapter(this, adapterList, R.layout.fileitem, adapterFrom, adapterTo);
		fileView.setAdapter(fileAdapter);
		
	}
}

class ReaderFileFilter implements FileFilter {

	@Override
	public boolean accept(File pathname) {
		if (pathname.isDirectory()) return true;
		String name = pathname.getName();
		int dotIndex = name.lastIndexOf('.');
		if (dotIndex == -1) return false;
		String extendName = name.substring(dotIndex + 1);
		
		if (extendName.equalsIgnoreCase("txt")) return true;
		if (extendName.equalsIgnoreCase("lnd")) return true;
		if (extendName.equalsIgnoreCase("htm")) return true;
		if (extendName.equalsIgnoreCase("html")) return true;
		return false;
	}
	
}